#include "tokenStorage.h"
#include "httpJsonClient.h"
#include "deviceCode.h"
#include "hardware.h"
#include "stringUtils.h"

TokenStorage::TokenStorage()
{
}

TokenStorage::~TokenStorage()
{
}

TokenStorage& TokenStorage::inst()
{
    static TokenStorage instance;
    return instance;
}

TokenInfo& TokenStorage::getToken() throw (AppException)
{
    if (token.nearestExpire()) {
        HttpJsonClient client;
        client.cancelToken();
        Char buf[SERIALNUM_LENTH] = { 0 };
        swprintf_s(buf, L"{\"code\":\"%s\"}", DeviceCode::inst().getDeviceCode());
        client.post("userserver/devices/token", buf);
        if (!client.requestSuccess()) {
            throw AppException(client.getErrorMessage().c_str());
        }
        TokenRes token;
        token.jsonDeserialize(client.getResponse());
        if (!token.isSuccess()) {
            throw AppException(StringUtils::Wstring2string(token.getMessage().c_str()).c_str());
        }
        this->token = token.getToken();
    }
    return token;
}

AccessKey& TokenStorage::getAccessKey() throw(AppException)
{
    if (accessKey.nearestExpire()) {
        HttpJsonClient client;
        client.get("movieserver/obs/readAccessKey");
        if (!client.requestSuccess()) {
            throw AppException(client.getErrorMessage().c_str());
        }
        AccessKeyRes res;
        res.jsonDeserialize(client.getResponse());
        if (!res.isSuccess()) {
            throw AppException(StringUtils::Wstring2string(res.getMessage().c_str()).c_str());
        }
        this->accessKey = res.getAccessKey();
    }
    return accessKey;
}
